<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="../org/angular.min.js"></script>
    <script src="../org/jquery.min.js"></script>
    <script src="../org/angular-ui-router.min.js"></script>
</head>

<body>

<div ng-app="hd">
    <div ui-view></div>
</div>

<script>
    var m = angular.module('hd', ['ui.router']);

    m.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        //默认路由（没有匹配的情况下显示这个锚点）
        $urlRouterProvider.otherwise('/home');
        //定义路由规则
        $stateProvider
            .state('home', {
                url: '/home',
                templateUrl: 'view/home.html',
                controller: 'ctrl'
            })
            .state('users', {
                url: '/users/{id}',
                template: '<h1>用户名：{{user.name}}</h1>',
                controller: 'ctrl'
            })
    }])

    m.service('getUser', ['$scope', function ($scope) {
            this.get = function (id) {
                if (id) {
                    for (var i = 0; i < $scope.users.length; i++) {
                        if (id == $scope.users[i].id) {
                            $scope.user = $scope.users[i];
                        }
                    }
                }
            }
    }]);

    //使用服务实现
    m.service('getUser', ['$stateParams', function($stateParams) {
        this.myFunc = function (users) {
            if ($stateParams.id) {
                for (var i = 0; i < users.length; i++) {
                    if ($stateParams.id == users[i].id) {
                        return users[i];
                    }
                }
            }
        }
    }]);

    //通过注入$stateParams服务获取url中所带的参数
    m.controller('ctrl', ['$scope', '$stateParams','getUser', function ($scope, $stateParams, getUser) {
        $scope.users = [
            {id: 1, name: '张三丰'},
            {id: 2, name: '李四点'}
        ];

        $scope.user = getUser.myFunc($scope.users);


       /* if ($stateParams.id) {
            for (var i = 0; i < $scope.users.length; i++) {
                if ($stateParams.id == $scope.users[i].id) {
                    $scope.user = $scope.users[i];
                }
            }
        }*/

    }]);

</script>

</body>

</html>